//
//  MusicDetailViewController.m
//  音乐播放器练习
//
//  Created by wyh on 16/3/30.
//  Copyright © 2016年 吴岳恒. All rights reserved.
//

#import "MusicDetailViewController.h"
#import "UIImageView+WebCache.h"
#import "musicModel.h"
#import "AudioPlayer.h"
@interface MusicDetailViewController ()<AVAudioPlayerDelegate,UITableViewDataSource>

///时间计时器


@end

@implementation MusicDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
//    NSLog(@"%ld",self.index);
    self.lrcAll = [NSMutableArray new];
    self.lrcTime = [NSMutableArray new];
    self.navigationController.navigationBar.alpha = 0.6;
    
    //设置歌词tableView
    self.lrcTabelView.backgroundColor = [UIColor clearColor];
    self.lrcTabelView.dataSource = self;
    self.lrcTabelView.separatorStyle = 0;
    self.lrcTabelView.showsVerticalScrollIndicator = NO;
    
    
    
    //设置标题
    [self setSongTitle];
    //设置歌词
    musicModel *model = self.musicArray[self.index];
    [self createLrcWith:model.lyric];
    //设置图片
    [self setBackGroudImage];
    [self setDiskPicImage:model.picUrl];
    
    //设置滑块
    self.slider.maximumValue = 10;
    //旋转滑块270度
    self.slider.transform = CGAffineTransformMakeRotation(1.57079633 * 3);
    //计时器
    [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
    
    
}

- (IBAction)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    self.block(self.index);
    NSLog(@"%ld",(long)self.index);
}

//设置歌词的即时滚动
-(void)ScrollCell
{
    float current = [AudioPlayer shareInstance].player.currentTime;
    NSString *currentStr = [NSString stringWithFormat:@"%.1f",current];
//    NSLog(@"%@",currentStr);检验
    for (int i = 0; i < self.lrcTime.count; i++) {

        if ([currentStr isEqualToString:self.lrcTime[i]]) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [self.lrcTabelView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.lrcAll.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.text = self.lrcAll[indexPath.row];
    cell.textLabel.textColor = [UIColor cyanColor];
    //设置cell文字的高亮状态
    cell.textLabel.highlightedTextColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.9 alpha:1];
    //设置文字全部显示
    cell.textLabel.numberOfLines = 0;
    //设置选中状态下的cell的背景
    UIView *view = [[UIView alloc]initWithFrame:CGRectZero];
    view.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = view;
    return cell;
}

//创建歌词
-(void)createLrcWith:(NSString *)str{
    NSArray *array = [str componentsSeparatedByString:@"\n"];
    
    NSMutableArray *arr1 = [NSMutableArray new];
    NSMutableArray *arr2 = [NSMutableArray new];
    for (NSString *str in array) {
        NSArray *singleArray = [str componentsSeparatedByString:@"]"];
        if (singleArray.count > 1) {
            NSString *lrc = singleArray.lastObject;
            
            ///获得时间
            NSString *timeStr = singleArray.firstObject;
            NSArray *timeArray = [timeStr componentsSeparatedByString:@":"];
            NSInteger min = [timeArray.firstObject substringFromIndex:1].integerValue;
            float second = min * 60 + [timeArray.lastObject floatValue];
            NSString *time = [NSString stringWithFormat:@"%.1f",second];
            
           
            
            [arr1 addObject:lrc];
            [arr2 addObject:time];
        }
    }
        self.lrcAll = arr1;
        self.lrcTime = arr2;
}
//更新时间
-(void)updateTime{
    
    
    NSInteger current = [AudioPlayer shareInstance].player.currentTime;
    NSInteger total = [AudioPlayer shareInstance].player.duration;
    self.currentTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",current/60,current%60];
    self.totalTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",total/60,total%60];
    double rate = [AudioPlayer shareInstance].player.currentTime / [AudioPlayer shareInstance].player.duration;
    self.progressSlider.value = rate;//设置滑块的移动
    [self ScrollCell];
}
//上一曲
- (IBAction)previousSongAction:(id)sender {
    
    self.index--;
    if (self.index < 0) {
        self.index = self.musicArray.count - 1;
    }
    musicModel *model = [self.musicArray objectAtIndex:self.index];
    [self setBackGroudImage];
    [self musicPlayWith:model.mp3Url];
    [self setSongTitle];
    [self createLrcWith:model.lyric];
    [self setDiskPicImage:model.picUrl];
    [self.lrcTabelView reloadData];
}
//暂停
- (IBAction)pauseSongAction:(id)sender {
    if (self.playOrPause == YES) {
        [[AudioPlayer shareInstance].player play];
        //再次设置为NO
        self.playOrPause = NO;
        [self.pause setImage:[UIImage imageNamed:@"iconfont-yinlezanting"] forState:(UIControlStateNormal)];
       
        
    }
    else
    {
        [[AudioPlayer shareInstance].player pause];
        //从新设置为YES
        self.playOrPause = YES;
        [self.pause setImage:[UIImage imageNamed:@"iconfont-bofangqibofang"] forState:(UIControlStateNormal)];
       
    }
    
}
//下一曲
- (IBAction)nextSongAction:(id)sender {
    self.index++;
    if (self.index == self.musicArray.count) {
        self.index = 0;
    }
    musicModel *model = [self.musicArray objectAtIndex:self.index];
    [self setBackGroudImage];
    [self musicPlayWith:model.mp3Url];
    [self setSongTitle];
    [self createLrcWith:model.lyric];
    [self setDiskPicImage:model.picUrl];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.lrcTabelView reloadData];
    });
    
}
//播放音乐
-(void)musicPlayWith:(NSString *)str{
    NSURL *url = [NSURL URLWithString:str];
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    dispatch_queue_t queue = dispatch_queue_create("com.wyh", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        [AudioPlayer shareInstance].player = [[AVAudioPlayer alloc]initWithData:data error:nil];
        
        [[AudioPlayer shareInstance].player prepareToPlay];
        
        [AudioPlayer shareInstance].player.delegate = self;
        
        [AudioPlayer shareInstance].player.volume = 5;
        
        [[AudioPlayer shareInstance].player play];
        
    });
    
    
}
//设置光盘图片
-(void)setDiskPicImage:(NSString *)Str{
    
    self.picImage.layer.cornerRadius = 100;
    self.picImage.layer.masksToBounds = YES;
    [self.picImage sd_setImageWithURL:[NSURL URLWithString:Str]];
    
    
    [self startDiskAnimation];
}
//开启动画
-(void)startDiskAnimation{
    CAKeyframeAnimation *ani = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];//设置旋转属性
    
    CGFloat point = M_PI_4;
    
    
    ani.values = @[@(9 * point),@(8 * point),@(7 * point),@(6 * point),@(5 * point),@(4 * point),@(3 * point),@(2 * point),@(point)];
    
    ani.repeatCount = MAXFLOAT;
    
    ani.duration = 5;

    
    [self.picImage.layer addAnimation:ani forKey:@"asd"];
}
//设置图片
-(void)setBackGroudImage
{
    //设置按钮初始状态
    [self.pause setImage:[UIImage imageNamed:@"iconfont-yinlezanting"] forState:(UIControlStateNormal)];
   
    
    musicModel *model = [self.musicArray objectAtIndex:self.index];
    [self.image sd_setImageWithURL:[NSURL URLWithString:model.blurPicUrl]];
}
//设置标题
-(void)setSongTitle{
    musicModel *model = [self.musicArray objectAtIndex:self.index];
    self.navigationItem.title = model.name;
}

//调节声音
- (IBAction)sliderAction:(UISlider *)sender {
    
    [AudioPlayer shareInstance].player.volume = sender.value;
    
}
//调节进度
- (IBAction)progressSliderAction:(UISlider *)sender {
    
    double current = sender.value * [AudioPlayer shareInstance].player.duration;
    [[AudioPlayer shareInstance].player setCurrentTime:current];
    
}
//自动下一曲
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    id sender;
    [self nextSongAction:sender];
    
}
@end
